package com.zking.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    public void findAll() {
        System.out.println("[UserService] 当前线程：" + Thread.currentThread().getName());
        try {
            // 模仿长时间工作
            System.out.println("开始服务：发送大量信息……");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("\t\t~~~发送完成……");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    
    @Async // 表示给后台的线程处理【自动的】
    public void findAllAsync() {
        System.out.println("[UserService] 当前线程：" + Thread.currentThread().getName());
        try {
            // 模仿长时间工作
            System.out.println("[Async] 开始服务：发送大量信息……");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("\t\t[Async] ~~~发送完成……");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    
    private int i = 1;
    
    @Async
    @Scheduled(fixedDelay = 5000) // 固定时间运行一次，无需手动
    public void task() {
        System.out.println("系统服务已经稳定运行：【" + i + "】次！" + "-" + Thread.currentThread().getName());
        i ++;
    }
}
